package com.xingzhe.content.service.Impl;

import com.xingzhe.content.mapper.CourseCategoryMapper;
import com.xingzhe.content.model.dto.CourseCategoryTreeDto;
import com.xingzhe.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Resource
    CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //调用mapper递归查询分类信息
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //找到每个节点的子节点，最终封装成list<CourseCategoryTreeDto>
        //先将list转为map,key就是节点id,value就是CourseCategoryTreeDto,目的就是方便从map获取节点，再通过filter过滤掉根节点
        Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //定义一个list作为最终返回的list
        List<CourseCategoryTreeDto> categoryTreeDtoArrayList = new ArrayList<>();
        //从头遍历courseCategoryTreeDtos，一边遍历一边找子节点放在父节点的childrenTreeNodes
        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            //往list添加父节点
            if (item.getParentid().equals(id)){
                categoryTreeDtoArrayList.add(item);
            }
            //从map找到节点的父节点
            CourseCategoryTreeDto courseCategoryParents = mapTemp.get(item.getParentid());
            //判断list里有没有该节点的父节点
            if (courseCategoryParents!=null){
                //如果改父节点的ChildrenTreeNodes属性为空则new一个集合，因为要向改集合放入它的子节点
                if (courseCategoryParents.getChildrenTreeNodes()==null){
                    courseCategoryParents.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                //然后将每个节点的子节点放到他的父节点的ChildrenTreeNodes属性中
                courseCategoryParents.getChildrenTreeNodes().add(item);
            }
        });
        return categoryTreeDtoArrayList;
    }
}
